package com.learning.platform.service;

import com.learning.platform.dto.CourseResponse;
import com.learning.platform.entity.Course;
import com.learning.platform.entity.Enrollment;
import com.learning.platform.exception.BusinessException;
import com.learning.platform.enums.ErrorCode;
import com.learning.platform.repository.CourseRepository;
import com.learning.platform.repository.EnrollmentRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EnrollmentService {
    
    private final EnrollmentRepository enrollmentRepository;
    private final CourseRepository courseRepository;
    private final CourseService courseService;
    
    public EnrollmentService(EnrollmentRepository enrollmentRepository,
                           CourseRepository courseRepository,
                           CourseService courseService) {
        this.enrollmentRepository = enrollmentRepository;
        this.courseRepository = courseRepository;
        this.courseService = courseService;
    }
    
    /**
     * 用户选课
     */
    @Transactional
    public void enrollCourse(Long userId, Long courseId) {
        // 检查课程是否存在
        Course course = courseRepository.findById(courseId)
            .orElseThrow(() -> new BusinessException(ErrorCode.COURSE_NOT_FOUND));
        
        // 检查是否已选课
        if (enrollmentRepository.existsByUserIdAndCourseId(userId, courseId)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "您已经选过此课程了");
        }
        
        // 创建选课记录
        Enrollment enrollment = new Enrollment();
        enrollment.setUserId(userId);
        enrollment.setCourseId(courseId);
        enrollmentRepository.save(enrollment);
        
        // 更新课程选课人数
        updateCourseEnrollmentCount(courseId);
    }
    
    /**
     * 取消选课
     */
    @Transactional
    public void unenrollCourse(Long userId, Long courseId) {
        Enrollment enrollment = enrollmentRepository.findByUserIdAndCourseId(userId, courseId)
            .orElseThrow(() -> new BusinessException(ErrorCode.PARAM_ERROR, "您未选过此课程"));
        
        enrollmentRepository.delete(enrollment);
        
        // 更新课程选课人数
        updateCourseEnrollmentCount(courseId);
    }
    
    /**
     * 检查用户是否已选课
     */
    public boolean isEnrolled(Long userId, Long courseId) {
        return enrollmentRepository.existsByUserIdAndCourseId(userId, courseId);
    }
    
    /**
     * 获取用户的选课列表
     */
    public Page<CourseResponse> getUserEnrolledCourses(Long userId, int page, int pageSize) {
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        Page<Enrollment> enrollments = enrollmentRepository.findByUserIdOrderByCreatedAtDesc(userId, pageable);
        
        return enrollments.map(enrollment -> {
            Course course = courseRepository.findById(enrollment.getCourseId()).orElse(null);
            if (course == null) return null;
            
            return new CourseResponse(course);
        });
    }
    
    /**
     * 更新课程选课人数
     */
    private void updateCourseEnrollmentCount(Long courseId) {
        long count = enrollmentRepository.countByCourseId(courseId);
        Course course = courseRepository.findById(courseId).orElse(null);
        if (course != null) {
            course.setEnrollmentCount((int) count);
            courseRepository.save(course);
        }
    }
}
